﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Configuration;

public partial class yzadmin_data_collect_manhuazhu : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    private JObject result = new JObject();

    string domain = "http://www.manhuazhu.com";
    string baseUrl = "http://www.manhuazhu.com/book.do?mc={0}&doing=book_web_search&page={1}";
    string updateUrl = "http://www.manhuazhu.com/xingeng/{0}/";
    string mc = "";
    int page = 1;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "single":
                    this.ProcessSingle();
                    break;
                case "import":
                    this.ProcessImport();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessImport()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            string[] urlArray = Request["zjurl"].Split('\n');
            Array.Reverse(urlArray);//数组倒序
            foreach (string url in urlArray)
            {
                HtmlDocument doc = webClient.Load(url);
                string js = doc.DocumentNode.SelectSingleNode("//script[last()]").InnerText;
                List<string> tpurl = new List<string>();
                MatchCollection collection = Regex.Matches(js, @"pic\[\d+\] \= \'([\S]+)\';");
                foreach (Match match in collection)
                {
                    tpurl.Add(match.Groups[1].Value);
                }
                YuuzleComic.Model.zj zj = new YuuzleComic.Model.zj();
                zj.cid = Convert.ToInt32(Request["id"]);
                zj.zjmc = doc.DocumentNode.SelectSingleNode("//h1").InnerText.Replace(doc.DocumentNode.SelectSingleNode("//div[1]/a[2]").InnerText, "").Trim();
                zj.time = DateTime.Now;
                zj.isdownload = false;
                zj.tpadd = Request["tpadd"] + zj.zjmc.Split(' ')[0] + "/";
                zj.tps = tpurl.Count;
                zj.tpurl = string.Join("|", tpurl.ToArray());
                YuuzleComic.BLL.zj zjbll = new YuuzleComic.BLL.zj();
                if (urlArray.Length == 1 && !string.IsNullOrEmpty(Request["zjid"]))
                {
                    zj.id = int.Parse(Request["zjid"]);
                    zjbll.Update(zj);
                }
                else
                {
                    zjbll.Add(zj);
                }
            }
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private string getUrl() {
        return string.IsNullOrEmpty(mc) ? string.Format(updateUrl, new object[] { page }) : string.Format(baseUrl, new object[] { mc, page });
    }

    private void ProcessSingle()
    {
        try
        {
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(Request["url"]);
            HtmlNode node = doc.DocumentNode.SelectSingleNode("//*[@class=\"cartoon-intro\"]");
            result.Add("mhmc", doc.DocumentNode.SelectSingleNode("//div[@class='book01']/h1/a").InnerText);
            result.Add("mhfm", domain + doc.DocumentNode.SelectSingleNode("//div[@class='book01']/a/img").Attributes["src"].Value);
            result.Add("zzmc", doc.DocumentNode.SelectSingleNode("//div[@class='book01']/text()[last()]").InnerText.Replace("作者：", "").Replace(" ", ","));
            result.Add("zt", doc.DocumentNode.SelectSingleNode("//div[@class='book02']/br[2]").NextSibling.InnerText.Trim().Replace("漫画状态：", ""));
            List<string> lblist = new List<string>();
            foreach (HtmlNode leibie in doc.DocumentNode.SelectNodes("//div[@class='book02']/a[starts-with(@href,'/leibie')]"))
            {
                lblist.Add(leibie.InnerText);
            }
            result.Add("classname", string.Join(",", lblist.ToArray()));
            result.Add("time", doc.DocumentNode.SelectSingleNode("//div[@class='book02']/br[5]").NextSibling.InnerText.Trim().Replace("更新时间：", ""));
            result.Add("mhjj", doc.DocumentNode.SelectSingleNode("//div[@class='bookb']").InnerText.Trim());
            result.Add("mhjs", doc.DocumentNode.SelectSingleNode("//div[@class='bookb']").InnerHtml);
            JArray chapters = new JArray();
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='bookd']/ul/li");
            if (nodes != null)
            {
                foreach (HtmlNode item in nodes)
                {
                    JObject chapter = new JObject();
                    chapter.Add("zjmc", item.SelectSingleNode("a").InnerText);
                    chapter.Add("zjurl", domain + item.SelectSingleNode("a").Attributes["href"].Value);
                    chapters.Add(chapter);
                }
            }
            result.Add("chapters", chapters);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        try
        {
            mc = Request["query"] == null ? "" : Request["query"].Trim();
            page = Convert.ToInt32(Request["page"]);
            HtmlWeb webClient = this.getWebClient();
            HtmlDocument doc = webClient.Load(this.getUrl());
            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//div[@class='yingcontent3']/li");
            JArray data = new JArray();
            foreach (HtmlNode node in nodes)
            {
                string s = !string.IsNullOrEmpty(mc) ? "div/" : "";
                JObject jo = new JObject();
                jo.Add("mhmc", node.SelectSingleNode(s + "a[2]").InnerText);
                jo.Add("mhurl", domain + node.SelectSingleNode(s + "a[2]").Attributes["href"].Value);
                jo.Add("zjmc", node.SelectSingleNode(s + "span/a").InnerText);
                jo.Add("zt", node.SelectSingleNode(s + "font").InnerText);
                data.Add(jo);
            }
            result.Add("data", data);
            result.Add("total", doc.GetElementbyId("mypage").SelectSingleNode("span").InnerText.Split(new string[] { "页", "条" }, StringSplitOptions.None)[1]);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }

    }

    private HtmlWeb getWebClient()
    {
        HtmlWeb webClient = new HtmlWeb();
        HtmlAgilityPack.HtmlWeb.PreRequestHandler handler = delegate(HttpWebRequest request)
        {
            request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
            request.CookieContainer = new System.Net.CookieContainer();
            request.Timeout = 500000;
            if (ConfigurationManager.AppSettings.Get("ProxyDomain").Contains(domain))
            {
                request.Proxy = new WebProxy(ConfigurationManager.AppSettings.Get("Proxy"));
            }
            return true;
        };
        webClient.PreRequest += handler;
        
        return webClient;
    }
}